﻿using LeSoft.Application.Bussiness;
using LeSoft.Application.Code;
using LeSoft.Application.Entity;
using LeSoft.Util;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace LeSoft.Application.Web.Areas.AuthorizeManage.Controllers
{
    /// <summary>
    /// 版 本 1.0
    /// Copyright (c) 2016 上海乐软信息技术有限公司
    /// 创建人：pl
    /// 日 期：2016.08.25
    /// 描 述：用户权限
    /// </summary>
    public class PermissionUserController : MvcControllerBase
    {
        private OrganizeBLL organizeBLL = new OrganizeBLL();
        private DepartmentBLL departmentBLL = new DepartmentBLL();
       // private RoleBLL roleBLL = new RoleBLL();
        //private UserBLL userBLL = new UserBLL();
        private ModuleBLL moduleBLL = new ModuleBLL();
        private AppModuleBLL appmoduleBLL = new AppModuleBLL();
        private ModuleButtonBLL moduleButtonBLL = new ModuleButtonBLL();
        private ModuleColumnBLL moduleColumnBLL = new ModuleColumnBLL();
        private PermissionBLL permissionBLL = new PermissionBLL();

       


        #region 视图功能
        /// <summary>
        /// 用户权限
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Enforce)]
        public ActionResult AllowAuthorize()
        {
            return View();
        }
        /// <summary>
        /// App权限
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Enforce)]
        public ActionResult AllowAPPAuthorize()
        {
            return View();
        }
        #endregion

        #region 获取数据
        /// <summary>
        /// 系统功能列表
        /// </summary>
        /// <param name="userId">用户Id</param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult ModuleTreeJson(string userId)
        {
            int chState = 0;
            var existModule = permissionBLL.GetModuleList(userId);
           var data = moduleBLL.GetList().Where(t => t.EnabledMark == 1).ToList();
           
           // var data = new AuthorizeBLL().GetModuleList(SystemInfo.CurrentUserId);
            var treeList = new List<TreeEntity>();
            if (data.Count() == existModule.Count()) chState = 1;
            string guid = Guid.NewGuid().ToString();
            treeList.Add(new TreeEntity() { id = guid, value = guid, text = "全选", parentId = "0", showcheck = true, checkstate = chState, hasChildren = true, isexpand = true, complete = true });
        
            foreach (ModuleEntity item in data)
            {
                TreeEntity tree = new TreeEntity();
                bool hasChildren = data.Count(t => t.ParentId == item.ModuleId) == 0 ? false : true;
                tree.id = item.ModuleId;
                tree.text = item.FullName;
                tree.value = item.ModuleId;
                tree.title = "";
                tree.checkstate = existModule.Count(t => t.ItemId == item.ModuleId);
                tree.showcheck = true;
                tree.isexpand = true;
                tree.complete = true;
                tree.hasChildren = hasChildren;
                if (item.ParentId == "0") tree.parentId = guid;
                else tree.parentId = item.ParentId;
                tree.img = "fa fa-square";
                treeList.Add(tree);
            }
            return Content(treeList.TreeToJson());
        }

        [HttpGet]
        public ActionResult APPModuleTreeJson(string userId)
        {  
            //int chState=0;
            var existModule = permissionBLL.GetAPPModuleList(userId);
            var data = appmoduleBLL.GetList().Where(t=> t.EnabledMark==1).ToList();
            var treeList = new List<TreeEntity>();
            //if(data.Count() == existModule.Count())  chState=1;
            //string guid=Guid.NewGuid().ToString();
            //treeList.Add(new TreeEntity() { id = guid, value = guid, text = "全选", parentId = "0", showcheck = true, checkstate =chState, hasChildren = true, isexpand = true, complete = true });
            foreach (AppModuleEntity item in data)
            {
                TreeEntity tree = new TreeEntity();
                bool hasChildren = data.Count(t => t.ParentId == item.Id) == 0 ? false : true;
                tree.id = item.Id;
                tree.text = item.Name;
                tree.value = item.Id;
                tree.title = "";
                tree.checkstate = existModule.Count(t => t.AppModuleId == item.Id);
                tree.showcheck = true;
                tree.isexpand = true;
                tree.complete = true;
                tree.hasChildren = hasChildren;
                if (item.ParentId == "0")
                {
                   // tree.parentId = guid;
                    tree.parentId = item.ParentId;
                    tree.img = "fa fa-mobile";
                }
                else
                {
                    tree.parentId = item.ParentId;
                    tree.img = "fa fa-square";
                }
                treeList.Add(tree);
            }
            return Content(treeList.TreeToJson());
        }
        /// <summary>
        /// 系统按钮列表
        /// </summary>
        /// <param name="userId">用户Id</param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult ModuleButtonTreeJson(string userId)
        {
            int chState = 0;
            var existModuleButton = permissionBLL.GetModuleButtonList(userId);
            var moduleData = new AuthorizeBLL().GetModuleList(SystemInfo.CurrentUserId);
            var moduleButtonData = new AuthorizeBLL().GetModuleButtonList(SystemInfo.CurrentUserId);
            var treeList = new List<TreeEntity>();
            if (moduleButtonData.Count() == existModuleButton.Count()) chState = 1;
            string guid = Guid.NewGuid().ToString();
            treeList.Add(new TreeEntity() { id = guid, value = guid, text = "全选", parentId = "0", showcheck = true, checkstate = chState, hasChildren = true, isexpand = true, complete = true });
           
            foreach (ModuleEntity item in moduleData)
            {
                TreeEntity tree = new TreeEntity();
                tree.id = item.ModuleId;
                tree.text = item.FullName;
                tree.value = item.ModuleId;
                tree.checkstate = existModuleButton.Count(t => t.ItemId == item.ModuleId);
                tree.showcheck = true;
                tree.isexpand = true;
                tree.complete = true;
                tree.hasChildren = true;
                if (item.ParentId == "0") tree.parentId = guid;
                else tree.parentId = item.ParentId;
                tree.img = item.Icon;
                treeList.Add(tree);
            }
            foreach (ModuleButtonEntity item in moduleButtonData)
            {
                TreeEntity tree = new TreeEntity();
                bool hasChildren = moduleButtonData.Count(t => t.ParentId == item.ModuleButtonId) == 0 ? false : true;
                tree.id = item.ModuleButtonId;
                tree.text = item.FullName;
                tree.value = item.ModuleButtonId;
                if (item.ParentId == "0")
                {
                    tree.parentId = item.ModuleId;
                }
                else
                {
                    tree.parentId = item.ParentId;
                }
                tree.checkstate = existModuleButton.Count(t => t.ItemId == item.ModuleButtonId);
                tree.showcheck = true;
                tree.isexpand = true;
                tree.complete = true;
                tree.img = "fa fa-wrench " + item.ModuleId;
                tree.hasChildren = hasChildren;
                treeList.Add(tree);
            }
            return Content(treeList.TreeToJson());
        }
        /// <summary>
        /// 系统视图列表
        /// </summary>
        /// <param name="userId">用户Id</param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult ModuleColumnTreeJson(string userId)
        {
            int chState = 0;
            var existModuleColumn = permissionBLL.GetModuleColumnList(userId);   
            var moduleData = new AuthorizeBLL().GetModuleList(SystemInfo.CurrentUserId);
            var moduleColumnData = new AuthorizeBLL().GetModuleColumnList(SystemInfo.CurrentUserId);
            var treeList = new List<TreeEntity>();
            if (moduleColumnData.Count() == existModuleColumn.Count()) chState = 1;
            string guid = Guid.NewGuid().ToString();
            treeList.Add(new TreeEntity() { id = guid, value = guid, text = "全选", parentId = "0", showcheck = true, checkstate = chState, hasChildren = true, isexpand = true, complete = true });
          
            foreach (ModuleEntity item in moduleData)
            {
                TreeEntity tree = new TreeEntity();
                tree.id = item.ModuleId;
                tree.text = item.FullName;
                tree.value = item.ModuleId;
                tree.checkstate = existModuleColumn.Count(t => t.ItemId == item.ModuleId);
                tree.showcheck = true;
                tree.isexpand = true;
                tree.complete = true;
                tree.hasChildren = true;
                if (item.ParentId == "0") tree.parentId = guid;
                else tree.parentId = item.ParentId;
                tree.img = item.Icon;
                treeList.Add(tree);
            }
            foreach (ModuleColumnEntity item in moduleColumnData)
            {
                TreeEntity tree = new TreeEntity();
                bool hasChildren = moduleColumnData.Count(t => t.ParentId == item.ModuleColumnId) == 0 ? false : true;
                tree.id = item.ModuleColumnId;
                tree.text = item.FullName;
                tree.value = item.ModuleColumnId;
                if (item.ParentId == "0")
                {
                    tree.parentId = item.ModuleId;
                }
                else
                {
                    tree.parentId = item.ParentId;
                }
                tree.checkstate = existModuleColumn.Count(t => t.ItemId == item.ModuleColumnId);
                tree.showcheck = true;
                tree.isexpand = true;
                tree.complete = true;
                tree.img = "fa fa-filter " + item.ModuleId;
                tree.hasChildren = hasChildren;
                treeList.Add(tree);
            }
            return Content(treeList.TreeToJson());
        }
       


        /// <summary>
        /// 数据权限列表
        /// </summary>
        /// <param name="userId">用户Id</param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult OrganizePstructTreeJson(string userId,int AuthorizeDataType)
        {            
            var existAuthorizeData = permissionBLL.GetAuthorizeDataList(userId);
            var treeList = new List<TreeEntity>();
            if (AuthorizeDataType == -1) return null;
            else
            {
                if (AuthorizeDataType > -1)
                {
                    #region 机构
                    var organizedata = organizeBLL.GetList();
                    foreach (OrganizeEntity item in organizedata)
                    {
                        TreeEntity tree = new TreeEntity();
                        bool hasChildren = organizedata.Count(t => t.ParentId == item.OrganizeId) == 0 ? false : true;
                        if (AuthorizeDataType > 0) hasChildren = true;
                        tree.id = item.OrganizeId;
                        tree.text = item.FullName;
                        tree.value = item.OrganizeId;
                        tree.title = "0";//机构
                        tree.parentId = item.ParentId;
                        if (item.ParentId == "0")
                        {
                            tree.img = "fa fa-sitemap";
                        }
                        else
                        {
                            tree.img = "fa fa-home";
                        }
                        tree.checkstate = existAuthorizeData.Count(t => t.ResourceId == item.OrganizeId);
                        tree.showcheck = true;
                        tree.isexpand = true;
                        tree.complete = true;
                        tree.hasChildren = hasChildren;                       
                        treeList.Add(tree);
                    }
                    #endregion
                }
                if (AuthorizeDataType > 0)
                {
                    var pstructdata = new PStructBLL().GetList().Where(t => t.Type <= AuthorizeDataType && t.Type != 3).OrderBy(t => t.Code);                   
                    foreach (PStructEntity item in pstructdata)
                    {
                        TreeEntity tree = new TreeEntity();
                        bool hasChildren = pstructdata.Count(t => t.ParentId == item.Id) == 0 ? false : true;
                        tree.id = item.Id;
                        tree.text = item.Name;
                        tree.value = item.Id;
                        tree.title = item.Type.ToString();//房产类型
                        if (item.ParentId == "0")
                        {
                            tree.parentId = item.OrganizeId;
                        }
                        else
                        {
                            tree.parentId = item.ParentId;
                        }
                        tree.checkstate = existAuthorizeData.Count(t => t.ResourceId == item.Id);
                        tree.showcheck = true;
                        tree.isexpand = true;
                        tree.complete = true;
                        tree.img = "fa fa-umbrella";
                        tree.hasChildren = hasChildren;                       
                        treeList.Add(tree);
                    }
                }
            }
            int authorizeType = -1;
            if (existAuthorizeData.ToList().Count > 0)
            {
                authorizeType = existAuthorizeData.ToList()[0].AuthorizeType.ToInt();
            }
            var JsonData = new
            {
                authorizeType = authorizeType,
                authorizeData = existAuthorizeData,
                treeJson = treeList.TreeToJson(),
            };
            return Content(JsonData.ToJson());
        }
        #endregion

        #region 提交数据
        /// <summary>
        /// 保存用户授权
        /// </summary>
        /// <param name="userId">用户Id</param>
        /// <param name="moduleIds">功能Id</param>
        /// <param name="moduleButtonIds">按钮Id</param>
        /// <param name="moduleColumnIds">视图Id</param>
        /// <param name="authorizeDataJson">数据权限</param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        [AjaxOnly]
        public ActionResult SaveAuthorize(string userId, string moduleIds, string moduleButtonIds,int AuthorizeDataType, string authorizeDataJson)
        {
            permissionBLL.SaveAuthorize(AuthorizeTypeEnum.User, userId, moduleIds, moduleButtonIds, AuthorizeDataType,authorizeDataJson);
            return Success("保存成功。");
        }

        /// <summary>
        /// 保存用户APP授权
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="moduleIds"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        [AjaxOnly]
        public ActionResult SaveAuthorizeAppModule(string userId, string moduleIds, int AuthorizeDataType,  string authorizeDataJson)
        {
            permissionBLL.SaveAuthorizeAppModule(AuthorizeTypeEnum.User, userId, moduleIds,  AuthorizeDataType,authorizeDataJson);
            return Success("保存成功。");
        }
        #endregion
    }
}
